import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from tqdm import tqdm
import torch.nn.functional as F
import matplotlib.pyplot as plt

# 数据预处理
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])

# 加载 CIFAR-10 数据集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=8, shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=8, shuffle=False, num_workers=2)

# 定义模型

class ANFISLayer(nn.Module):
    def __init__(self, input_dim, S=2, T=16, learning_rate=0.01):
        super(ANFISLayer, self).__init__()
        self.S = S
        self.T = T
        self.learning_rate = learning_rate

        # Initialize parameters
        self.c1 = nn.Parameter(torch.empty(S, input_dim).uniform_(-1, 1))
        self.b1 = nn.Parameter(torch.empty(S, input_dim).uniform_(-1, 1))
        self.w1 = nn.Parameter(torch.empty(1, T).uniform_(0, 1))

    def forward(self, samplein):
        # Normalization
        samplein_min = samplein.min(dim=1, keepdim=True).values
        samplein_max = samplein.max(dim=1, keepdim=True).values
        sampleinnorm = (samplein - samplein_min) / (samplein_max - samplein_min)

        # Initialize output tensor
        Y = torch.zeros_like(sampleinnorm)

        # Compute membership degrees
        for m in range(sampleinnorm.shape[0]):
            u1 = torch.exp(-((sampleinnorm[m].unsqueeze(0) - self.c1) ** 2) / (self.b1 ** 2))

            # Rule generation layer
            alpha1 = torch.zeros(self.T, device=sampleinnorm.device)
            for i in range(self.S):
                a = 1 if i != 1 else 8
                for p in range(self.S):
                    b = 1 if p != 1 else 4
                    for q in range(self.S):
                        c = 1 if q != 1 else 2
                        for k in range(self.S):
                            idx = i * a + p * b + q * c + k
                            if idx < self.T:  # Ensure idx is within bounds
                                alpha1[idx] = u1[i, 0] * u1[p, 0] * u1[q, 0] * u1[
                                    k, 0]  # Index to get the first element

            alphasum = alpha1.sum()
            Y[m] = torch.dot(self.w1.squeeze(), alpha1) / alphasum if alphasum != 0 else 0

        return Y


class FCNN(nn.Module):
    def __init__(self, n_femap=4, stride=2, dropout=True, num_classes=10):
        super(FCNN, self).__init__()
        self.dropout = dropout
        self.conv1 = nn.Conv2d(3, 20, kernel_size=3, stride=1, padding=1)
        self.conv2 = nn.Conv2d(20, 40, kernel_size=3, stride=1, padding=1)
        self.conv3 = nn.Conv2d(40, 40, kernel_size=3, stride=1, padding=1)
        self.conv4 = nn.Conv2d(40, 40, kernel_size=3, stride=1, padding=1)
        self.conv5 = nn.Conv2d(40, n_femap, kernel_size=3, stride=stride, padding=1)
        self.anfis_layer = ANFISLayer(18 * 18)  # Use the ANFIS layer initialized here
        if self.dropout:
            self.dropout_layer = nn.Dropout(0.2)

        self.fc1 = nn.Linear(32*18*18, 128)  # Update based on the feature map size
        self.linear1 = nn.Linear(4*324, num_classes)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, kernel_size=3, stride=1, padding=1)

        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, kernel_size=2, stride=1, padding=1)
        x = F.relu(self.conv3(x))
        x = F.max_pool2d(x, kernel_size=2, stride=1, padding=1)
        x = F.relu(self.conv4(x))
        x = F.max_pool2d(x, kernel_size=2, stride=1, padding=1)
        x = F.relu(self.conv5(x))


        if self.dropout:
            x = self.dropout_layer(x)

        x = x.view(-1, 18 * 18)

        x = self.anfis_layer(x)  # 使用 self.anfis_layer，传入相应的输入和输出

        x = x.view(8,4*324)  # Ensure correct integer division

        out = self.linear1(x)

        return out


# 训练设置
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")  # 检查GPU是否可用
model = FCNN().to(device)  # 移动模型到GPU
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
losses = []

# 训练过程
num_epochs = 100  # 可以根据需要调整
for epoch in range(num_epochs):
    model.train()
    running_loss = 0.0
    for inputs, labels in tqdm(trainloader):
        inputs, labels = inputs.to(device), labels.to(device)  # 移动输入和标签到GPU

        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward(retain_graph=True)
        optimizer.step()

        running_loss += loss.item()

    print(f"Epoch [{epoch + 1}/{num_epochs}], Loss: {running_loss / len(trainloader):.4f}")
    losses.append(running_loss / len(trainloader))

# 绘制损失图
plt.plot(losses)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Training Loss Over Epochs')
plt.show()

# 测试过程
model.eval()
correct = 0
total = 0
with torch.no_grad():
    for inputs, labels in testloader:
        inputs, labels = inputs.to(device), labels.to(device)  # 移动输入和标签到GPU
        outputs = model(inputs)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print(f'Accuracy of the model on the 10000 test images: {100 * correct / total:.2f}%')
